package net.sudot.chess.business.wechat.handler;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sudot.chess.business.model.Customer;
import net.sudot.chess.business.model.SocialUser;
import net.sudot.chess.business.service.CustomerService;
import net.sudot.chess.business.service.SocialUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 微信关注事件处理
 *
 * @author tangjialin on 2017-05-04 0004.
 */
@Component
public class SubscribeHandler extends AbstractHandler {

    @Resource
    private SocialUserService socialUserService;
    @Resource
    private CustomerService customerService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        doHandle(wxMessage, context, wxMpService, sessionManager);
        return WxMpXmlOutMessage.TEXT().content("终于等到您，欢迎来到pai友圈[爱心]\n" +
                "点击【游戏大厅】，可在线报名约牌竞赛，胜利牌友还可获得现金红包哦[奸笑]\n" +
                "如有问题请添加客服MM微信：paiyou99\n" +
                "点击我的头像置顶公众号，福利滚滚来~[礼物]\n" +
                "祝您在游戏中玩的愉快！[愉快]")
                .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                .build();
    }

    public void doHandle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                         WxSessionManager sessionManager) {
        String fromUser = wxMessage.getFromUser();
        if (fromUser == null) { return; }
        SocialUser socialUser = socialUserService.findByUniqueId(wxMpService.getWxMpConfigStorage().getAppId(), fromUser);
        if (socialUser == null) { return; }
        socialUser.setSubscribe(true);
        socialUserService.update(socialUser);
        if (socialUser.getUserId() == null) { return; }
        Customer customer = customerService.find(socialUser.getUserId());
        if (customer == null || customer.getHead() != null) { return; }
        try {
            WxMpUser wxMpUser = wxMpService.getUserService().userInfo(socialUser.getUniqueId());
            customer.setHead(wxMpUser.getHeadImgUrl());
            customer.setNickname(wxMpUser.getNickname());
            customerService.update(customer);
        } catch (WxErrorException e) {
            logger.warn("用户关注公众号时,用户信息拉取异常", e);
        }
    }
}
